package login

import (
	"context"
	"database/sql"
	v1 "donkey-admin/api/login/v1"
	"donkey-admin/internal/dao"
	"donkey-admin/internal/model/entity"
	"donkey-admin/utility"
	"errors"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"
)

func (s *sLogin) Login(ctx context.Context, req *v1.AdminLoginReq) (res *v1.AdminLoginRes, err error) {

	var user entity.SysUser
	err = dao.SysUser.Ctx(ctx).Where("user_name", req.UserName).Scan(&user)
	if err != nil && errors.Is(err, sql.ErrNoRows) {
		g.Log().Error(ctx, err)
		return nil, gerror.New("用户不存在")
	}

	if !utility.BcryptCheck(req.PassWord, user.UserPasswd) {
		return nil, gerror.New("密码不正确")
	}

	token, err := utility.GenerateToken(ctx, user)
	if err != nil {
		return nil, err
	}

	roleMenuArray, err := dao.SysRoleMenu.Ctx(ctx).Fields("menu_id").
		Where("role_code", user.UserRole).Array()
	if err != nil {
		g.Log().Error(ctx, err)
		return nil, err
	}

	var menu []entity.SysMenu
	err = dao.SysMenu.Ctx(ctx).
		Where("menu_parent_id", "").
		Where("uuid", roleMenuArray).
		With(entity.SysMenu{}).Order("menu_order asc").Scan(&menu)
	if err != nil && errors.Is(err, sql.ErrNoRows) {
		g.Log().Error(ctx, err)
		return nil, err
	}

	return &v1.AdminLoginRes{
		Token:    token,
		UserInfo: user,
		UserMenu: menu,
	}, nil
}
